/**
 * Copyright (c) 2016-2019 九点科技 All rights reserved.
 *
 * http://www.9dyun.cn
 *
 * 版权所有，侵权必究！
 */
package com.dian.modules.sale.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dian.common.utils.*;

import com.dian.common.validator.ValidatorUtils;
import com.dian.common.validator.group.AddGroup;
import com.dian.common.validator.group.UpdateGroup;
import com.dian.modules.enums.sale.InstallHead_InstallStateEnum;
import com.dian.modules.enums.sale.OrderHead_InstallFlagEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dian.common.exception.RRException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.collections.CollectionUtils;
import com.dian.common.server.CommonService;
import com.dian.modules.sale.dao.InstallHeadDao;

import com.dian.modules.sale.entity.InstallLineEntity;
import com.dian.modules.sale.entity.InstallHeadEntity;

import com.dian.modules.sale.service.InstallHeadService;
import com.dian.modules.sale.service.InstallLineService;

import com.dian.modules.sale.vo.InstallHeadExportVO;
import com.dian.modules.sale.vo.InstallLineExportVO;

/**
 * 销售安装单服务实现类
 *
 * @author xiaolai
 * @email xiaolai@9dyun.cn
 * @date 2019-06-22 09:37:58
 */
@Service("installHeadService")
public class InstallHeadServiceImpl extends ServiceImpl<InstallHeadDao, InstallHeadEntity> implements InstallHeadService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    public CommonService commonService;

    @Autowired
    public InstallLineService installLineService;

    /**
     * 销售安装单分页
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<InstallHeadEntity> page = this.page(new Query<InstallHeadEntity>().getPage(params),getQueryWrapper(params) );
        return new PageUtils(page);
    }

    /**
    *  销售安装单新增
    * @param installHeadEntity
    * @return
    */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean saveInfo(InstallHeadEntity installHeadEntity) {

        //设置编码，等基础默然初始化数据设置
        installHeadEntity.setInstallNo(commonService.getCode(InstallHeadEntity.class));
        installHeadEntity.setInstallDate(new Date());


        //数据完整性校验
        this.paramsCheck(installHeadEntity,AddGroup.class);

        //保存主表
        this.save(installHeadEntity);

        //保存从表
        if (CollectionUtils.isNotEmpty(installHeadEntity.getInstallLineEntityList())) {
            List<InstallLineEntity> detailList = installHeadEntity.getInstallLineEntityList();
            for (InstallLineEntity detail : detailList) {
                detail.setInstallId(installHeadEntity.getId());
            }
            installLineService.saveBatch(installHeadEntity.getInstallLineEntityList());
        }
        return true;
    }

    /**
     *销售安装单更新
     * @param installHeadEntity
     * @return
     */
    @Override
    public boolean updateInfo(InstallHeadEntity installHeadEntity) {

        //修改状态校验
        this.updateCheck(installHeadEntity.getId());

        //主表数据完整性校验
        this.paramsCheck(installHeadEntity, UpdateGroup.class);

        //更新主表
        this.updateById(installHeadEntity);

        //更新从表
        installLineService.updateInfo(installHeadEntity);


        return true;
    }

    /**
     *销售安装单删除
     * @param id
     * @return
     */
    @Override
    public boolean deleteInfo(Long id) {

        //删除状态校验
        this.deleteCheck(id);

        //更新从表
        installLineService.deleteInfo(id);

        //更新主表
        this.remove(new QueryWrapper<InstallHeadEntity>().eq("id",id));

        return true;
    }

    /**
     * 销售安装单详情
     * @param id
     * @return
     */
    @Override
    public InstallHeadEntity getInfo(Long id) {
        InstallHeadEntity installHeadEntity =getById(id);
        List<InstallLineEntity> lineList=installLineService.queryLineList(id);
        installHeadEntity.setInstallLineEntityList(lineList);
        return installHeadEntity;
    }

    /**
     * 销售安装单审核
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean checkInfo(Long id) {
        InstallHeadEntity installHeadEntity =this.getById(id);
        checkCheck(installHeadEntity);
        installHeadEntity.setInstallState(InstallHead_InstallStateEnum.AUDITED.getValue());
        installHeadEntity.setCheckDate(new Date());
        installHeadEntity.setCheckUserId(commonService.getUserId());
        installHeadEntity.setCheckUserName(commonService.getUserName());
        return this.updateById(installHeadEntity);
    }

    /**
     *销售安装单当前页or全部导出
     * @param params
     * @return
     */
    @Override
    public List<InstallHeadExportVO> exportList(Map<String, Object> params) {
        List<InstallHeadEntity> list;
        Integer exprotType= PUtil.getParaToInt(params.get("exprotType"),0);
        if(exprotType==0){
            list= this.page(new Query<InstallHeadEntity>().getPage(params),getQueryWrapper(params)).getRecords();
        }else{
            list= this.list(getQueryWrapper(params));
        }
        List<InstallHeadExportVO> resultList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)) {
            resultList = BeanConverter.convertList(list, InstallHeadExportVO.class);
            // 封装明细
            if(CollectionUtils.isNotEmpty(resultList)){
                for(InstallHeadExportVO installHeadEntity : resultList){
                    List<InstallLineEntity>  installLineEntityList = installLineService.queryLineList(installHeadEntity.getId());
                    installHeadEntity.setInstallLineExportVOList(BeanConverter.convertList( installLineEntityList, InstallLineExportVO.class));
                }
            }
        }
        return resultList;
    }


    /***********************************************************************************************/
    /****************************************** 私有方法 ********************************************/
    /***********************************************************************************************/

    /**
     * 修改状态校验
     *
     * @param
     */
    private void updateCheck(Long id) {
        InstallHeadEntity installHeadEntity =this.getById(id);
        if(installHeadEntity.getInstallState().equals(InstallHead_InstallStateEnum.AUDITED.getValue())){
             throw new RRException(String.format("[%s] 当前订单为已审核状态,禁止修改",installHeadEntity.getInstallNo()));
        }
    }
    /**
     * 审核状态校验
     *
     * @param
     */
    private void checkCheck(InstallHeadEntity installHeadEntity) {

        if(installHeadEntity.getInstallState().equals(InstallHead_InstallStateEnum.AUDITED.getValue())){
          throw new RRException(String.format("[%s] 当前订单为已审核状态,禁止审核",installHeadEntity.getInstallNo()));
        }
    }

    /**
     * 删除状态校验
     *
     * @param
     */
    private void deleteCheck(Long id) {
         InstallHeadEntity installHeadEntity =this.getById(id);
         if(installHeadEntity.getInstallState().equals(InstallHead_InstallStateEnum.AUDITED.getValue())){
            throw new RRException(String.format("[%s] 当前订单为已审核状态,禁止删除",installHeadEntity.getInstallNo()));
         }
    }

    /**
     * 新增和修改参数校验
     *
     * @param record
     */
    private void paramsCheck(InstallHeadEntity record, Class<?> cls) {

        //设置明细的主表ID
        ListUtils.setPropertyValue(record.getInstallLineEntityList(),"install_id",record.getId());

        ValidatorUtils.validateEntity(record, cls);

        if (CollectionUtils.isEmpty(record.getInstallLineEntityList())) {
            throw new RRException("销售安装单明细数据不能为空");
        }
        for (InstallLineEntity installLineEntity : record.getInstallLineEntityList()) {
            int index = record.getInstallLineEntityList().indexOf(installLineEntity) + 1;
            try {
                ValidatorUtils.validateEntity(installLineEntity, cls);
            }catch (RRException e){
                throw new RRException(String.format("第%s行 预订单明细校验失败<br/>"+e.getMsg(), index));
            }
        }
    }

    /**
     * 获取查询条件
     *
     * @param
     */
    private QueryWrapper<InstallHeadEntity> getQueryWrapper(Map<String, Object> params) {
        QueryWrapper<InstallHeadEntity> queryWrapper=new QueryWrapper<>();
        if(!StrUtil.isBlankIfStr(params.get("installNo"))){
            queryWrapper.like("install_no",params.get("installNo"));
        }
    if(!StrUtil.isBlankIfStr(params.get("installDate"))){
        String installDate=String.valueOf(params.get("installDate"));
        String[] installDateRange=installDate.split("至");
        if(installDateRange.length==2){
            queryWrapper.gt("install_date",DateUtils.getBeginTimeOfDate(installDateRange[0]));
            queryWrapper.lt("install_date",DateUtils.getBeginTimeOfDate(installDateRange[1]));
        }else{
            queryWrapper.gt("install_date",DateUtils.getBeginTimeOfDate(installDate));
        }
    }
        if(!StrUtil.isBlankIfStr(params.get("probNo"))){
            queryWrapper.like("prob_no",params.get("probNo"));
        }
        if(!StrUtil.isEmptyIfStr(params.get("propKey"))){
            queryWrapper.and(wrapper -> wrapper
            );
        }
        if(!StrUtil.isBlankIfStr(params.get("probId"))){
            queryWrapper.eq("prob_id",params.get("probId"));
        }
        queryWrapper.orderByAsc("id");
        return queryWrapper;
    }
}
